<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="标题" :label-width="labelWidth" prop="title">
        <ElInput v-model="form.title" />
      </ElFormItem>
      <el-row>
        <el-col :span="12">
          <ElFormItem label="类型" :label-width="labelWidth" prop="type">
            <el-select v-model="form.type" :clearable="true" :fit-input-width="true">
              <el-option v-for="item in WorkDynamics.TypeEnum" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="创建时间" :label-width="labelWidth" prop="createTime">
            <el-date-picker
              v-model="form.createTime"
              type="date"
              value-format="YYYY-MM-DD"
              :disabled-date="createTimeDisabledDate" />
          </ElFormItem>
        </el-col>
      </el-row>
      <ElFormItem label="图片" :label-width="labelWidth" prop="icon">
        <UploadImg v-model:image-url="form.icon" :api="uploadAvatar" :fileSize="10">
          <template #tip>图片最大为 10M</template>
        </UploadImg>
      </ElFormItem>
      <el-row>
        <el-col :span="12">
          <ElFormItem label="经度" :label-width="labelWidth" prop="longitude">
            <ElInput v-model="form.longitude" />
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="纬度" :label-width="labelWidth" prop="latitude">
            <ElInput v-model="form.latitude" />
          </ElFormItem>
        </el-col>
      </el-row>
      <ElFormItem label="简介" :label-width="labelWidth" prop="content">
        <Editor v-model:value="editorValue" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance } from 'element-plus'
import { FormType } from '@/enums'
import { WorkDynamics, getWorkDynamicsDetail, saveOrUpdateWorkDynamics } from '@api/tby/community/workDynamics'
import Editor from '@/components/WangEditor/index.vue'
import { ElMessage } from 'element-plus'
import { uiUpload } from '@api/upload'
import UploadImg from '@/components/Upload/Img.vue'
import { dateFormat, validateLatitude, validateLongitude } from '@api/tby/common/common'

const editorValue = ref('')
const labelWidth = 100
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<WorkDynamics.Form>>({})

onMounted(async () => {
  console.log('进来了')
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

/**限制使用时间不能晚于当前时间 */
const createTimeDisabledDate = (time: any) => {
  return new Date(dateFormat(time.getTime(), 'yyyy-MM-dd')).getTime() > new Date().getTime()
}

const rules = reactive<FormRules>({
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { max: 20, message: '标题最大20个字符', trigger: 'blur' }
  ],
  type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
  createTime: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
  icon: [{ required: true, message: '请上传图片', trigger: 'blur' }],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { max: 32, message: '经度最大32个字符', trigger: 'blur' },
    { validator: validateLongitude, trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { max: 32, message: '纬度最大32个字符', trigger: 'blur' },
    { validator: validateLatitude, trigger: 'blur' }
  ]
})

const open = async (type: FormType, id?: number) => {
  form.value = {}
  formType.value = type
  editorValue.value = ''
  opened.value = true
  if (isAdd.value) {
    loading.value = false
  } else {
    try {
      const { data } = await getWorkDynamicsDetail(id!)
      loading.value = false
      form.value = data
      if (form.value.createTime) {
        form.value.createTime = dateFormat(parseFloat(form.value.createTime), 'yyyy-MM-dd')
      }
      if (data.content) {
        editorValue.value = data.content
      }
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
  editorValue.value = ''
  form.value = {}
}

// 上传头像
function uploadAvatar(formData: FormData) {
  return uiUpload('avatar', formData)
}

const onSaveClicked = () => {
  if (!formRef.value) {
    return
  }
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    if (editorValue.value == '') {
      ElMessage({
        type: 'error',
        message: '请输入介绍!'
      })
      return
    }
    const formData = { ...unref(form) }
    formData.content = editorValue.value
    saveOrUpdateWorkDynamics(formData).then(() => {
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
